<template>
	<view>
    <u-navbar title="收货地址管理" @leftClick="leftClick" bgColor="transparent"
              :titleStyle="{fontSize:'36rpx',fontWeight:'500'}">
    </u-navbar>
		<scroll-view class="container" scroll-y="true">
			<u-radio-group v-model="defaultAddress" @change="handleChange">
				<view class="address_group" v-if="addresses.length>0">
					<!-- 地址列表 -->
					<view class="addressitem" v-for="(address, index) in addresses" :key="index"
						@tap="addressReturn(address)">
						<u--text :text="`${address.person} ${address.mobile}`" size="14" bold color="#333"
							margin="0 0 32rpx"></u--text>
						<u--text :text="address.province+address.city+address.district+address.address" size="12"
							color="#666666"></u--text>
						<view class="line"></view>
						<view class="action_bar">
							<u-radio size="12" label-size="10" :name="address.id" label="选为默认"></u-radio>
							<text @tap.stop="editAddress(index)">编辑</text>
							<text @tap.stop="deleteAddress(address.id)">删除</text>
						</view>
					</view>
				</view>
				<view class="address_group" v-else>
					<u--text text="未设置回收地址" size="18" color="#666666" align="center"></u--text>
				</view>
        <view style="height: 150px"></view>
			</u-radio-group>
		</scroll-view>
<!--		<view class="bottomBtnDiv">-->
<!--			<view class="bottomBtn">-->
<!--				<u-button type="primary" text="添加收货地址" @tap="addNewAddress"></u-button>-->
<!--			</view>-->
<!--		</view>-->
		<view>
			<view style="width: 90%;margin: 0 auto">
				<u-button type="primary" text="添加收货地址" @tap="addNewAddress"></u-button>
			</view>
		</view>

		<!-- 地址编辑弹窗 -->
		<u-popup :show="showPopup" mode="center" custom-style="width:90%;border-radius:32rpx;">
			<view class="popup-content">
				<u-form ref="form" :model="currentAddress" :rules="rules" labelWidth="100">
					<u-form-item label="收货人" prop="person">
						<u-input v-model="currentAddress.person" placeholder="请输入收货人姓名" />
					</u-form-item>
					<u-form-item label="联系电话" prop="mobile">
						<u-input v-model="currentAddress.mobile" placeholder="请输入联系电话" />
					</u-form-item>
					<u-form-item label="地区" prop="region">
						<picker mode="region" :value="defaultRegion" @change="onRegionChange">
							<view class="region_select">
								<u--text :text="selectedRegion!==''?selectedRegion:'选择地区'"></u--text><u-icon
									name="arrow-right" color="#DDDDDD" size="14"></u-icon>
							</view>
						</picker>
					</u-form-item>
					<u-form-item label="详细地址" prop="address">
						<u-input v-model="currentAddress.address" placeholder="请输入详细地址" type="textarea" />
					</u-form-item>
					<u-form-item label="设为默认" prop="isDefault">
					<u-switch v-model="currentAddress.isDefault" :activeValue="1" :inactiveValue="0" />
					</u-form-item>
				</u-form>
				<view :style="{ marginBottom: '10rpx' }">
					<u-button type="success" @tap="saveCurrAddress">保存</u-button>
				</view>
				<u-button type="error" @tap="cancelEdit">取消</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getAddress,
		saveAddress,
		setDefaultAddress,
		delAddress
	} from "@/api/user.js";
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	export default {
		computed: {
			...mapState(["user"])
		},
		data() {
			return {
        text:'',
        address_id:null,
				defaultAddress: 0,
				// 地址数组
				addresses: [],
				defaultRegion: ["310000", "310100", "310101"],
				selectedRegion: "", // 用户选择的结果
				// 当前编辑的地址索引
				currentAddressIndex: null,
				// 当前编辑的地址对象
				currentAddress: {
					person: '',
					region: [],
					province: "",
					city: "",
					district: "",
					mobile: '',
					address: '',
					isDefault: 1
				},
				// 是否显示编辑弹窗
				showPopup: false,
				// 表单验证规则
				rules: {
					person: {
						required: true,
						message: '请输入收货人姓名',
						trigger: 'blur'
					},
					mobile: [{
						required: true,
						message: '请输入联系电话',
						trigger: 'blur'
					}, {
						validator: this.validatePhone,
						message: '请输入正确的手机号',
						trigger: ['blur', 'change']
					}],
					region: {
						validator: this.validateRegion,
						message: '请选择地区',
						trigger: ['blur', 'change']
					},
					address: {
						required: true,
						message: '请输入详细地址',
						trigger: 'blur'
					}
				}
			};
		},
		onLoad(option) {
      this.text = option.text
			this.getAddresses();

		},
		onReady() {
			this.$refs.form.setRules(this.rules); // 设置表单规则
		},
		methods: {
      leftClick() {
        uni.navigateBack();
        uni.$emit('ref',{data:this.addresses[0]})
      },
      addressReturn(e){
        if (this.text == '回收页'){
          var data = JSON.stringify(e)
          uni.$emit('ref',{data:e})
          uni.navigateBack();


          // var data = JSON.stringify(e)
          // const url = `/pages/recycle/create_recycle?AddressData=${data}`;
          // uni.navigateTo({
          //   url: url
          // });
        }
      },
			// 自定义验证方法
			validatePhone(rule, value, callback) {
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!value) {
					callback(new Error('请输入手机号')); // 如果为空，返回错误提示
				} else if (!phoneRegex.test(value)) {
					callback(new Error('请输入正确的手机号')); // 如果格式不正确，返回错误提示
				} else {
					callback(); // 验证通过
				}
			},
			validateRegion(rule, value, callback) {
				if (value.length === 0) {
					callback(new Error('请选择地区')); // 如果为空，返回错误提示
				} else {
					callback(); // 验证通过
				}
			},
			handleChange(e) {
				// this.setDefaultAdd(e);
				this.addDefaultAdd(e);
			},
			onRegionChange(e) {
				this.currentAddress.region = e.detail.value;
				this.selectedRegion = e.detail.value.join("-"); // 获取选择的省市区
			},
      //获取用户地址列表
			getAddresses() {
				let query = {
					username: this.user.username
				};
				getAddress(query).then(res => {
          this.addresses = res.data;
          let defaultAdd = res.data.find(item => {
            return item.is_default == "01"
          });
          if (defaultAdd) {
            this.defaultAddress = defaultAdd.id;
          }else{
            this.defaultAddress = null
          }

				}).catch(err => {
					console.error(err);
				})
			},

			// 编辑地址
			editAddress(index) {
				this.currentAddressIndex = index;
				let address = this.addresses[index];
				this.currentAddress = {
					id: address.id,
					person: address.person,
					mobile: address.mobile,
					address: address.address,
					isDefault: address.is_default * 1,
					region: [address.province, address.city, address.district],
					province: address.province,
					city: address.city,
					district: address.district,
				};
				this.defaultRegion = [address.province, address.city, address.district];
				this.selectedRegion = this.defaultRegion.join("-");
				this.showPopup = true;
			},
			// 删除地址
			deleteAddress(id) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该地址吗？',
					success: (res) => {
						if (res.confirm) {
							delAddress({
								id: id
							}).then(res => {
								if (res.code === 0) {
                  this.defaultAddress = null
									this.getAddresses();
								} else {
									uni.showToast({
										title: res.msg
									});
								}
							}).catch(err => {
								console.error(err);
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			// 添加新地址
			addNewAddress() {
				this.currentAddressIndex = null;
				this.currentAddress = {
					person: '',
					mobile: '',
					address: '',
					isDefault: 0,
					region: [],
					province: '',
					city: '',
					district: '',
				};
				this.showPopup = true;
			},
			// 保存地址
			saveCurrAddress() {
				this.$refs.form.validate().then(() => {
					saveAddress(this.currentAddress).then(async res => {
						if (this.currentAddress.isDefault == 1) {
							this.setDefaultAdd(res.data.id);
						}
						this.getAddresses();
            // this.getAddress();
						this.showPopup = false;
					}).catch(err => {
						console.error(err);
						this.showPopup = false;
					})
				}).catch(errors => {
					// 表单验证失败，errors 是包含所有验证错误的对象
					console.error('验证失败', errors);
				});
			},

      getAddress_new(){
        let query = {
          username: this.user.username
        };
        getAddress(query).then(res => {
          let defaultAdd = res.data.find(item => {
            return item.is_default == "01"
          });
          console.log("保存完地址",res.data)
          console.log("保存完地址寻找默认地址",defaultAdd)
          if (defaultAdd) {
            this.defaultAddress = defaultAdd.id;
          }
          this.addresses = res.data;
        }).catch(err => {
          console.error(err);
        })
      },
			// 保存地址
			setDefaultAdd(id) {
				setDefaultAddress({
					id: id
				}).then(res => {
          //this.defaultAddress = id;
					this.getAddresses();
				}).catch(err => {
					console.error(err);
					this.showPopup = false;
				})
			},
			// 点击默认地址
			addDefaultAdd(id) {
				setDefaultAddress({
					id: id
				}).then(res => {
				}).catch(err => {
					console.error(err);
					this.showPopup = false;
				})
			},
			// 取消编辑
			cancelEdit() {
				this.showPopup = false;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.popup-content {
		padding: 28rpx;
	}
  .region_select {
    display: flex;
    justify-content: space-between;
    align-items: center;

	}

	.address_group {
		width: 100%;

		.addressitem {
			padding: 40rpx 28rpx;
			margin-bottom: 20rpx;

			.line {
				border-top: 2rpx solid #e7e7e7;
				margin: 40rpx 0 20rpx;
			}

			.action_bar {
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #999999;
				font-size: 20rpx;
			}
		}
	}
</style>

